/**
 * Copyright (C), 2020, JieYi Software System Co., Ltd.
 * All rights reserved.
 * FileName:       MdmsUserService.java
 *
 * @Description:
 * @author: feiwe
 * Modification History:
 * Date         Author        Version        Discription
 * -------------------------------------------------------
 * 2020/11/11      feiwe                         add
 */


package com.fengwei.service;

import com.fengwei.dao.MdmsUserMapper;
import com.fengwei.form.MdmsUser;
import com.fengwei.requestdata.user.MdmsUserAddData;
import com.fengwei.requestdata.user.MdmsUserChangePasswordData;
import com.fengwei.requestdata.user.MdmsUserDelData;
import com.fengwei.requestdata.user.MdmsUserEditData;
import com.fengwei.requestdata.user.MdmsUserGetUsersForSshServerSignedData;
import com.fengwei.requestdata.user.MdmsUserPagingListData;
import com.fengwei.requestdata.user.MdmsUserResetMfaKeyData;
import com.fengwei.requestdata.user.MdmsUserResetPasswordData;
import com.fengwei.util.HexStringUtil;
import com.fengwei.util.MdmsConsts;
import com.fengwei.util.PltResult;
import com.fengwei.util.RSAUtil;
import com.fengwei.util.SnowflakeIdWorker;
import com.fengwei.util.VerifyException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.interfaces.RSAPrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MdmsUserService {
    private final static Logger logger = LoggerFactory.getLogger(MdmsUserService.class);

    @Autowired
    private MdmsUserMapper mdmsUserMapper;

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    public Map<String, Object> pagingList(MdmsUserPagingListData mdmsUserPagingListData) {
        Map mapPagingList = new HashMap();
        PageHelper.startPage(mdmsUserPagingListData.getPage(), mdmsUserPagingListData.getLimit());
        //String orderBy = SortConsts.getSortStr(mdmsUserPagingListData.getOrderby(), SortConsts.USER_ASC_DESC);
        Page<MdmsUser> list = mdmsUserMapper.selectByPage(mapPagingList);
        Map<String, Object> mapReturn = new HashMap();
        mapReturn.put("total", list.getTotal());
        mapReturn.put("limit", mdmsUserPagingListData.getLimit());
        mapReturn.put("page", mdmsUserPagingListData.getPage());
        mapReturn.put("list", list.getResult());
        return mapReturn;
    }

    public Map<String, Object> add(MdmsUserAddData mdmsUserAddData) throws Exception {
        Map<String, Object> returnData = new HashMap<>();
        Map mapSelectByUserCode = new HashMap();
        mapSelectByUserCode.put("userCode", mdmsUserAddData.getUserCode());
        MdmsUser mdmsUser = mdmsUserMapper.selectByUserCode(mapSelectByUserCode);
        if (null != mdmsUser) {
            // 用户已存在
            throw new VerifyException(PltResult.RESULT_CF013);
        } else {
            Map mapInsert = new HashMap();
            mapInsert.put("id", snowflakeIdWorker.nextId());
            mapInsert.put("userCode", mdmsUserAddData.getUserCode());
            mapInsert.put("userName", mdmsUserAddData.getUserName());
            mapInsert.put("userPassword", "40bd001563085fc35165329ea1ff5c5ecbdbbeef");
            mapInsert.put("userSex", mdmsUserAddData.getUserSex());
            mapInsert.put("mobileNo", mdmsUserAddData.getMobileNo());
            mapInsert.put("mailboxNo", mdmsUserAddData.getMailboxNo());
            mapInsert.put("userType", mdmsUserAddData.getUserType());
            mapInsert.put("userStatus", mdmsUserAddData.getUserStatus());
            mapInsert.put("pwderrTimes", 0);
            mapInsert.put("ifChangepwd", "N");
            mapInsert.put("mfaFlag", mdmsUserAddData.getMfaFlag());
            mdmsUserMapper.insert(mapInsert);

        }
        return returnData;
    }

    public Map<String, Object> edit(MdmsUserEditData mdmsUserEditData) {
        Map<String, Object> returnData = new HashMap<>();
        Map mapSelectByPrimaryKey = new HashMap();
        mapSelectByPrimaryKey.put("id", mdmsUserEditData.getId());
        MdmsUser mdmsUser = mdmsUserMapper.selectByPrimaryKey(mapSelectByPrimaryKey);
        if (null == mdmsUser) {
            // 用户不存在
            throw new VerifyException(PltResult.RESULT_CF012);
        } else {
            MdmsUser mdmsUserUpdate = new MdmsUser();
            mdmsUserUpdate.setId(mdmsUser.getId());
            mdmsUserUpdate.setUserCode(mdmsUserEditData.getUserCode());
            mdmsUserUpdate.setUserName(mdmsUserEditData.getUserName());
            mdmsUserUpdate.setUserSex(mdmsUserEditData.getUserSex());
            mdmsUserUpdate.setMobileNo(mdmsUserEditData.getMobileNo());
            mdmsUserUpdate.setMailboxNo(mdmsUserEditData.getMailboxNo());
            mdmsUserUpdate.setUserType(mdmsUserEditData.getUserType());
            mdmsUserUpdate.setMfaFlag(mdmsUserEditData.getMfaFlag());
            mdmsUserUpdate.setUserStatus(mdmsUserEditData.getUserStatus());
            mdmsUserMapper.update(mdmsUserUpdate);
        }

        return returnData;
    }

    public Map<String, Object> del(MdmsUserDelData mdmsUserDelData) {
        Map<String, Object> returnData = new HashMap<>();
        Map mapSelectByPrimaryKey = new HashMap();
        mapSelectByPrimaryKey.put("id", mdmsUserDelData.getId());
        MdmsUser mdmsUser = mdmsUserMapper.selectByPrimaryKey(mapSelectByPrimaryKey);
        if (null == mdmsUser) {
            // 用户不存在
            throw new VerifyException(PltResult.RESULT_CF012);
        } else {
            MdmsUser mdmsUserDel = new MdmsUser();
            mdmsUserDel.setId(mdmsUser.getId());
            mdmsUserMapper.delete(mdmsUserDel);
        }

        return returnData;
    }

    public Map<String, Object> changePassword(MdmsUserChangePasswordData mdmsUserChangePasswordData, HttpServletRequest request, MdmsUser mdmsUser) throws Exception {
        Map<String, Object> returnData = new HashMap<>();
        HttpSession session = request.getSession();
        logger.debug("session.getId():" + session.getId());

        String[] rsaKeyPair = (String[]) session.getAttribute(mdmsUserChangePasswordData.getOtpCode());
        session.removeAttribute(mdmsUserChangePasswordData.getOtpCode());
        String modulus = rsaKeyPair[0];
        String exponentPri = rsaKeyPair[1];
        RSAPrivateKey rsaPrivateKey = RSAUtil.loadPrivateKey(modulus, exponentPri, 16);

        byte[] oldPlainText = RSAUtil.privateKeyDecrypt("RSA", "ECB", "PKCS1Padding", rsaPrivateKey,
                HexStringUtil.hexStringToBytes(mdmsUserChangePasswordData.getOldUserPassword()));
        String oldpassword = new String(oldPlainText);
        logger.info("oldpassword:" + oldpassword);

        byte[] plainText = RSAUtil.privateKeyDecrypt("RSA", "ECB", "PKCS1Padding", rsaPrivateKey, HexStringUtil.hexStringToBytes(mdmsUserChangePasswordData.getUserPassword()));
        String password = new String(plainText);
        logger.info("password:" + password);

        Map mapSelectByPrimaryKey = new HashMap();
        mapSelectByPrimaryKey.put("id", mdmsUser.getId());
        MdmsUser mdmsUserInDB = mdmsUserMapper.selectByPrimaryKey(mapSelectByPrimaryKey);
        if (null == mdmsUser) {
            // 用户不存在
            throw new VerifyException(PltResult.RESULT_CF012);
        } else {
            if (!oldpassword.equals(mdmsUserInDB.getUserPassword())) {
                logger.error("密码错误");
                throw new VerifyException(PltResult.RESULT_CF005);
            } else {
                MdmsUser mdmsUserUpdate = new MdmsUser();
                mdmsUserUpdate.setId(mdmsUserInDB.getId());
                mdmsUserUpdate.setUserPassword(password);
                mdmsUserUpdate.setIfChangepwd("1");
                mdmsUserMapper.update(mdmsUserUpdate);
            }
        }

        return returnData;
    }

    public Map<String, Object> resetPassword(MdmsUserResetPasswordData mdmsUserResetPasswordData, HttpServletRequest request,
                                             MdmsUser mdmsUserSession) {
        Map<String, Object> returnData = new HashMap<>();
        Map mapSelectByPrimaryKey = new HashMap();
        mapSelectByPrimaryKey.put("id", mdmsUserResetPasswordData.getId());
        MdmsUser mdmsUser = mdmsUserMapper.selectByPrimaryKey(mapSelectByPrimaryKey);
        if (null == mdmsUser) {
            // 用户不存在
            throw new VerifyException(PltResult.RESULT_CF012);
        } else {
            MdmsUser mdmsUserUpdate = new MdmsUser();
            mdmsUserUpdate.setId(mdmsUser.getId());
            mdmsUserUpdate.setUserPassword("40bd001563085fc35165329ea1ff5c5ecbdbbeef");
            mdmsUserUpdate.setIfChangepwd(MdmsConsts.IF_CHANGEPWD_N);
            mdmsUserUpdate.setPwderrTimes(0L);
            mdmsUserMapper.update(mdmsUserUpdate);
        }
        return returnData;
    }

    public Map<String, Object> resetMfaKey(MdmsUserResetMfaKeyData mdmsUserResetMfaKeyData, HttpServletRequest request, MdmsUser mdmsUserSession) {
        Map<String, Object> returnData = new HashMap<>();
        Map mapSelectByPrimaryKey = new HashMap();
        mapSelectByPrimaryKey.put("id", mdmsUserResetMfaKeyData.getId());
        MdmsUser mdmsUser = mdmsUserMapper.selectByPrimaryKey(mapSelectByPrimaryKey);
        if (null == mdmsUser) {
            // 用户不存在
            throw new VerifyException(PltResult.RESULT_CF012);
        } else {
            MdmsUser mdmsUserResetMfaKey = new MdmsUser();
            mdmsUserResetMfaKey.setId(mdmsUser.getId());
            mdmsUserMapper.resetMfaKey(mdmsUserResetMfaKey);
        }
        return returnData;
    }

    public Map<String, Object> getUsersForSshServerSigned(MdmsUserGetUsersForSshServerSignedData mdmsUserGetUsersForSshServerSignedData, MdmsUser mdmsUser, HttpServletRequest request) {
        Map<String, Object> returnData = new HashMap<>();
        Map mapGetUsersForSshServerSigned = new HashMap();
        mapGetUsersForSshServerSigned.put("serverUserId", mdmsUserGetUsersForSshServerSignedData.getServerUserId());
        List<MdmsUser> userList = mdmsUserMapper.getUsersForSshServerSigned(mapGetUsersForSshServerSigned);
        List<MdmsUser> unsignedUserList = mdmsUserMapper.getUsersForSshServerUnsigned(mapGetUsersForSshServerSigned);
        returnData.put("signedList", userList);
        returnData.put("unsignedList", unsignedUserList);
        return returnData;
    }

}
